package com.hry.sunflower.controller;

import com.hry.sunflower.common.Constant;
import com.hry.sunflower.common.ServerResponse;
import com.hry.sunflower.pojo.User;
import com.hry.sunflower.service.UserService;
import com.hry.sunflower.util.CookieUtil;
import com.hry.sunflower.util.DataCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 用户登录
     * @param user
     * @param request
     * @return
     */
    @PostMapping("user/login")
    @ResponseBody
    public ServerResponse userLogin(User user, HttpServletRequest request) {
        // 校验邮箱格式和数据是否为空
        if (!DataCheck.checkEmail(user.getEmail().trim()) || StringUtils.isEmpty(user.getEmail())) {
            return ServerResponse.createByErrorMessage("邮箱格式不正确！");
        }
        // 取数据查询数据
        User userInfo = userService.getUserInfo(user, Constant.IN_NET);
        if (null == userInfo) {
            return ServerResponse.createByErrorMessage("用户名或密码错误");
        }
        // 写用户信息到session中
        request.getSession(true).setAttribute(Constant.CURRENT_USER, userInfo);
        return ServerResponse.createBySuccess("登录成功", CookieUtil.getValueByCookie(Constant.LOGIN_BACK_RUL, request));
    }

    /**
     * 用户退出
     */
    @RequestMapping("user/logout")
    public String logoutUser(HttpServletRequest request) {
        request.getSession(true).invalidate();
        return "login";
    }


}
